package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import domain.User;
import exception.LoginException;
import exception.RegisterException;
import service.UserServlet;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.UUID;


public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //第一步：提取参数，
        User user=null;
        Response build=null;
        try {
            JSONObject object = GetRequestJsonUtils.getRequestJsonObject(req);
            String user_str = object.getString("user");
            // 第二步：转换参数成java对象；
            user = JSON.parseObject(user_str, User.class);
            UUID uuid = UUID.randomUUID();//生成一个随机的字母串，不会出现相同的字母串
            user.setActiveCode(uuid.toString());
        }catch (Exception e){
           e.printStackTrace();
           build=Response.build(ResponseCode.ERROR_PARAMS);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());
            return;
        }
        // 第三步：去查询数据库表中是否有这个记录；
        UserServlet userServlet = new UserServlet();
        try {
            userServlet.register(user);//注册成功,返回成功消息
            build = Response.build(ResponseCode.OK_REGISTER);
        } catch (RegisterException e) {//登录异常，返回异常消息
            e.printStackTrace();
            build = Response.build(e.getError());
        }
        //第四步：判断为空，则返回登录失败的消息，。。。。；
        //第五步：把消息对象转换成字符串，返回浏览器
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());
    }
}
